<template>
  <div>
    <basic-container>内容管理 / 插画管理 / 头像库</basic-container>
    <!-- <basic-container>
      <el-button type="primary" @click="flag = !flag"
        >切换有无数据(测试使用)</el-button
      >
    </basic-container> -->

    <!-- 有内容 -->
    <div v-if="flag">
      <!-- 未启动管理展示 start-->
      <basic-container v-if="!flagcheck">
        <!-- 上传按钮 -->
        <el-upload
          class="upload-demo"
          :action="catUrl + '/file/uploadFile'"
          multiple
          ref="my-upload"
          :on-success="successimage"
          :auto-upload="false"
          :on-change="onChange"
          :limit="10"
          :file-list="fileList"
          :on-exceed="OnExceed"
        >
          <el-button type="">添加图片</el-button>
        </el-upload>
        <el-button type="" @click="flagcheck = !flagcheck">管理</el-button>
        <el-button type="primary" v-if="fileList.length!=0" @click="submitUpload">上传</el-button>
      </basic-container>
      <!-- 未启动管理展示 end-->

      <!-- 点击管理展示的内容start -->
      <basic-container v-if="flagcheck">
        <el-button type="" @click="flagcheck = !flagcheck">退出管理</el-button>
        <el-button>全选</el-button>
        <el-button @click="delHeadImage">删除</el-button>
      </basic-container>
      <!-- 点击管理展示的内容end -->

      <!-- 展示列表 start-->
      <el-row :gutter="20">
        <!-- 数据内容是查询出来的,内容是id和图片路径还有checked属性-true,false,后端去处理是否修改了列表. 选择图片,可删除-->
        <el-col :span="4" v-for="(data,i) in imageList" :key="i">
          <div class="block">
            <el-image :src="data.image_url" style="border-radius: 8px">
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
            <!-- 选择按钮 -->
            <el-checkbox v-if="flagcheck" v-model="checked"></el-checkbox>
          </div>
        </el-col>
      </el-row>
      <!-- 展示列表end -->
    </div>

    <!-- 无数据,只显示添加头像按钮 -->
    <div v-if="!flag">
      <!-- 上传按钮 start -->
      <el-upload
        multiple
        ref="my-upload"
        :action="catUrl + '/file/uploadFile'"
        list-type="picture-card"
        :on-success="successimage"
        :limit="10"
        :on-exceed="OnExceed"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <!-- 上传按钮end -->
    </div>
  </div>
</template>

<script>
import { common } from "@/api/cat/httpRequest";
import { catUrl } from "@/config/env";
import { appHeadImageLibrary as baseURL, uploadFile } from "@/api/cat/baseUrls";
export default {
  data() {
    return {
      flag: false,
      flagcheck: false,
      checked: true,
      imageList: [],
      flagImage: false,
      tempImageCount: 0,
      fileList: [],
      count:0
    };
  },
  async created() {
    this.getList();
  },

  // created() {
  //   this.$confirm("请您先不要进来,俺还没好,快出去", "提示", {
  //     confirmButtonText: "出去",
  //     cancelButtonText: "不出去",
  //     type: "warning",
  //   })
  //     .then(() => {
  //       this.$alert("OK。那咱们出去啦~", "出去出去~", {
  //         confirmButtonText: "出去",
  //         callback: (action) => {
  //           this.$router.go(-1);
  //         },
  //       });
  //     })
  //     .catch(() => {
  //       this.$alert("想不出去?不行,必须出去", "出去出去~", {
  //         confirmButtonText: "出去",
  //         callback: (action) => {
  //           this.$router.go(-1);
  //         },
  //       });
  //     });
  // },
  methods: {
    //删除
    delHeadImage() {
      //这里将修改后的头像库列表传入后台,根据check判断是否删除即可,false表示已删除
      this.$confirm("确定要删除吗？已使用的头像的id将会恢复默认头像?", "提示", {
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handlePreview(file) {},
    async getList() {
      //查询是否有头像库数据,修改flag条件
      let { data } = await common(baseURL.list, null, null, "GET");
      if (data == null) {
        this.flag = false;
        return;
      }
      if (data.length == 0) {
        this.flag = false;
        return;
      }
      this.flag = true;
      this.imageList = data;
    },
    // 多上传函数
    async submitUpload() {
      //上传函数，如果把提交函数用在http-request钩子中，fileList多长就执行请求多少次接口，依旧是无法做到只请求一次上传多文件
      var formData = new FormData(); //  用FormData存放上传文件
      this.fileList.forEach((file) => {
        formData.append("reportFile", file.raw, file.raw.name); //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
      });
      //上传           :action="catUrl + '/file/uploadFile'"
     let data = await common(`/file/uploadFiles`,formData,null,"POST")
    
      if(data.code==1){
        let  data2  = await common(
        baseURL.addImage,
        { image_url: data.data.join(",") },
        null,
        "POST"
      );

        this.$refs["my-upload"].clearFiles();
        this.flag = true; //展示头像列表
        this.getList();

      }

    },

    /**头像上传成功 */
    async successimage(response, file, fileList) {
      if (this.flagImage) {
        return;
      }
      //http://res.xsdoudou.com/doudoumanager/11.jpg
      //添加到头像库中
      let  data  = await common(
        baseURL.addImage,
        { image_url: response.source },
        null,
        "POST"
      );
      if (data == null) {
        this.$message.error("上传失败");
      } else {
        //上传成功,清除列表
        this.$refs["my-upload"].clearFiles();
        this.flag = true; //展示头像列表
        this.getList();
      }
      this.flagImage = true;
    },
    onChange(file, fileList) {
      //这里做一些文件控制，注意：就算一次选取多个文件，这里依旧会执行多次
      const isJPG = file.raw.type === "image/jpeg"|| file.raw.type==="image/png"||file.raw.type==='image/gif';
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG/GIF 格式!");
        fileList.pop();
      }
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find((f) => f.name === file.name);
      if (existFile) {
        this.$message.error("当前文件已经存在!");
        fileList.pop();
      }
      this.fileList = fileList;
    },
    // 上传数达到最大数量时
    OnExceed(file, fileList) {
      this.$message.error(`1次最多只能上传10张图片!`);
    },
  },
};
</script>

<style>
.el-col {
  border-radius: 8px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>